﻿using System;
using System.Linq;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Http;
using ELearning.Common.Model;
using ELearning.Common.Oprator;
using ELearning.Models;
using ELearning.Models.ViewModel.Account;
using ELearning.Models.ViewModel.YTJYAdmin.Account;
using SiteAPI.Controllers.Common;

namespace SiteAPI.Controllers.Account
{
    /// <summary>
    /// 账号相关
    /// </summary>
    public class LoginController : BaseApiController
    {
        /// <summary>
        /// 用户操作service
        /// </summary>
        private ESysUserService userService = new ESysUserService();

        /// <summary>
        /// 组织操作service
        /// </summary>
        private EOrgService orgService => new EOrgService();

        /// <summary>
        /// 注册日志操作service
        /// </summary>
        private TRegisterLogService tRegisterLogService => new TRegisterLogService();

        /// <summary>
        /// 登录token记录操作service
        /// </summary>
        private TLoginTokenService tlLoginTokenService => new TLoginTokenService();

        /// <summary>
        /// 登录接口
        /// </summary>
        [HttpPost, Route("api/ELogin/Login")]
        [AllowAnonymous]
        public ServiceResponse<AdminLoginViewModel> Login(AdminLoginRequest request)
        {
            if (request.IsNull())
                return ServiceResponse<AdminLoginViewModel>.ErrorResponse("参数不能为空");
            var p = request.Password.Trim();
            var users = userService.FindList(u => !u.IsDelete && u.LoginName == request.LoginName.Trim());
            var viewModel = new AdminLoginViewModel();
            if (users.IsNotNull() && users.Any())
            {
                var user = users.FirstOrDefault(u => !u.IsDelete && u.LoginName == request.LoginName.Trim() && u.Password == p);
                if (user.IsNotNull())
                {
                    viewModel = new AdminLoginViewModel
                    {
                        Token = GuidUtil.NewSequentialId().ToString(),
                        HeadPhoto = PictureHelper.GetFileFullPath(user.HeadPhoto),
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserName = user.UserName,
                        CardNo = user.CardNo
                    };
                    var currentUserModel = new OperatorModel
                    {
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        LoginName = user.LoginName,
                        OrgCode = user.OrgCode,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserId = user.UserID,
                        UserIp = IpHelp.GetClientIp(),
                        UserName = user.UserName,
                        UserType = user.UserType,
                        CardNo = user.CardNo
                    };

                    //保存登录token日志
                    tlLoginTokenService.Add(new TLoginToken
                    {
                        Id = Guid.NewGuid(),
                        CreateTime = DateTime.Now,
                        CreateUserId = user.UserID,
                        IsDelete = false,
                        PassDateTime = DateTime.Now.AddHours(8),
                        Token = viewModel.Token,
                        UpdateTime = DateTime.Now,
                        UpdateUserId = user.UserID,
                        UserId = user.UserID,
                        Source = 1
                    });
                    WriteHelper.WriteFile($"viewModel.Token----{viewModel.Token}");
                    WriteHelper.WriteFile($"currentUserModel----{currentUserModel.ToJson()}");
                    OperatorProvider.Provider.AddCurrent(viewModel.Token, currentUserModel);
                    return ServiceResponse<AdminLoginViewModel>.SuccessResponse(viewModel);
                }
                return ServiceResponse<AdminLoginViewModel>.SuccessResponse(CommonConst.PASSWORD_ERROR, viewModel, CommonConst.PASSWORD_ERROR_CODE);

            }

            return ServiceResponse<AdminLoginViewModel>.SuccessResponse(CommonConst.USER_NOT_EXIST, viewModel, CommonConst.USER_NOT_EXIST_CODE);
        }

        [HttpPost, Route("api/ELogin/GetCache")]
        [AllowAnonymous]
        public object GetCache(string token)
        {
            var str = OperatorProvider.Provider.GetCurrent(token);

            return str;
        }

        /// <summary>
        /// 注册
        /// </summary>
        [HttpPost, Route("api/ELogin/Register")]
        [AllowAnonymous]
        public ServiceResponse<bool> Register(RegisterRequest request)
        {
            var user = userService.Find(u => !u.IsDelete && u.LoginName == request.MobilePhone);
            if (user.IsNotNull())
            {
                return ServiceResponse<bool>.SuccessResponse(CommonConst.USER_EXIST, false, CommonConst.USER_EXIST_CODE);
            }

            var orgCode = string.Empty;
            if (!string.IsNullOrEmpty(request.InviteCode))
            {
                //是否是用户的邀请码
                orgCode = userService.Find(u => !u.IsDelete && u.InviteCode == request.InviteCode)?.OrgCode;
                if (string.IsNullOrEmpty(orgCode))//不是用户的邀请码，判断是否为机构的邀请码
                {
                    orgCode = orgService.Find(o => !o.IsDelete && o.InviteCode == request.InviteCode)?.org_code ?? string.Empty;
                }
            }
            var inviteCode = GetInviteCode(user.OrgCode, user.UserID);
            var addUser = new ESysUser
            {
                IsDelete = false,
                UserID = Guid.NewGuid(),
                LoginName = request.MobilePhone,
                UserName = request.MobilePhone,
                UserType = UserType.UserTypeSTUDENT,
                MobilePhone = request.MobilePhone,
                InviteCode = inviteCode,
                CreateTime = DateTime.Now,
                AccountStatus = 1,
                OrgCode = orgCode,
                Password = request.Password.Trim(),
                ModifyTime = DateTime.Now,
                Birthday = DateTime.Now,
                Sex = 1,
                Email = string.Empty,
                CardNo = string.Empty,
                Remark = string.Empty,
                Modifyer = string.Empty,
                Company = string.Empty,
                Creater = string.Empty,
                Department = string.Empty,
                HeadPhoto = string.Empty,
                OfficeTel = string.Empty,
                Position = string.Empty,
                Unumber = string.Empty
            };
            userService.AddNoSaveChange(addUser);

            var log = new TRegisterLog
            {
                Id = Guid.NewGuid(),
                CreateUserId = CurrentUserModel.UserId,
                CreateTime = DateTime.Now,
                InviteCode = request.InviteCode,
                IsDelete = false,
                Status = 0,
                MobilePhone = request.MobilePhone,
                OrgCode = orgCode,
                UpdateUserId = CurrentUserModel.UserId,
                UpdateTime = DateTime.Now,
                UserId = addUser.UserID
            };
            tRegisterLogService.Add(log);

            return ServiceResponse<bool>.SuccessResponse(true);
        }

        /// <summary>
        /// 发版后使用，把用户登录的信息放到内存中，临时使用，使用。redis 后废弃
        /// </summary>
        [HttpPost, Route("api/ELogin/ResetCache")]
        [AllowAnonymous]
        public object ResetCache()
        {
            var tokens = tlLoginTokenService.FindList(l => !l.IsDelete && l.PassDateTime > DateTime.Now).ToList();
            var userIds = tokens.Select(l => l.UserId).ToList();
            var users = userService.FindList(u => !u.IsDelete && userIds.Contains(u.UserID)).ToList();

            foreach (var user in users)
            {
                var currentUserModel = new OperatorModel
                {
                    Email = user.Email,
                    HeadPhoto = user.HeadPhoto,
                    LoginName = user.LoginName,
                    OrgCode = user.OrgCode,
                    //OrgName = orgService.Find(w => w.org_code == user.OrgCode)?.org_name ?? string.Empty,
                    MobilePhone = user.MobilePhone,
                    Position = user.Position,
                    Remark = user.Remark,
                    UserId = user.UserID,
                    UserIp = IpHelp.GetClientIp(),
                    UserName = user.UserName,
                    UserType = user.UserType,
                };
                var token = tokens.Where(l => l.UserId == user.UserID).OrderByDescending(l => l.PassDateTime).FirstOrDefault();

                if (token.IsNotNull())
                {
                    OperatorProvider.Provider.AddCurrent(token.Token, currentUserModel, token.PassDateTime);
                }

            }
            return true;
        }
    }
}